package com.example.emailcraft.interceptor;

import com.example.emailcraft.entity.dto.CurrentUser;
import com.example.emailcraft.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Slf4j
public class AuthInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        // 1. 放行登录接口
        if ("/api/v1/users/login".equals(request.getRequestURI())) {
            return true;
        }
        // 2. 放行注册
        if (request.getRequestURI().startsWith("/api/v1/users/register")) {
            return true;
        }

        // 2. 获取令牌
        String token = getTokenFromCookie(request);
        log.info("token: {}", token);
        if (token == null) {
            sendError(response, "缺少认证令牌");
            return false;
        }

        // 3. 验证令牌
        if (!JwtUtil.validateToken(token)) {
            sendError(response, "无效或过期的令牌");
            return false;
        }

        // 4. 存储用户信息
        CurrentUser user = new CurrentUser(
                JwtUtil.getUserId(token),
                JwtUtil.getUsername(token),
                JwtUtil.getRoles(token)
        );
        CurrentUserHolder.set(user);

        return true;
    }


    private String getTokenFromCookie(HttpServletRequest request) {
        // 获取所有 Cookie
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                // 查找名为 "token" 的 Cookie
                if ("token".equals(cookie.getName())) {
                    return cookie.getValue(); // 返回 Token
                }
            }
        }
        return null; // 如果没有找到 Token，返回 null
    }

    private void sendError(HttpServletResponse response, String msg) throws IOException {
        response.setStatus(401);
        response.setContentType("application/json");
        response.getWriter().write("{\"code\":" + 401 + ",\"message\":\"" + msg + "\"}");
    }
}
